﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Threading;
using System.Media;

namespace EOffice.Presentation
{
    public partial class frmPrivateChat : Form
    {
        private IPEndPoint receiveport;
        private UdpClient udpclient;
        private string localuser;
        private string desti;
        private Thread waitpackets;
        private IPEndPoint ipendpoint;
        public frmPrivateChat()
        {
            InitializeComponent();
        }
        public void Privareroomopen(int number, IPEndPoint ip, string localname, string dest)
        {
            ipendpoint = ip;
            localuser = localname;
            desti = dest;
            try
            {
                udpclient = new UdpClient(number + 5000);
            }
            catch
            {
                MessageBox.Show("This port using by another program");
            }
            receiveport = new IPEndPoint(new IPAddress(0), (0));
            waitpackets = new Thread(new ThreadStart(waitForPackets));
            waitpackets.IsBackground = true;
            waitpackets.Start();
            this.Text = "Private Chat - " + dest;
        }
        public void waitForPackets()
        {
            while (true)
            {
                try
                {
                    byte[] data = udpclient.Receive(ref receiveport);
                    //udpclient.Send(data, data.Length, receiveport);
                    IPEndPoint newuser = new IPEndPoint(receiveport.Address, receiveport.Port);
                    WriteTextBoxDes(System.Text.Encoding.Unicode.GetString(data));
                }
                catch 
                {
                }
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            WriteTextBox(textBox1.Text);
            SendMessage(textBox1.Text);
            textBox1.Clear();
        }

        public void SendMessage(string a)
        {
            byte[] sending = System.Text.Encoding.Unicode.GetBytes("M" + a.ToString());
            udpclient.Send(sending, sending.Length, ipendpoint);
        }

        public void WriteTextBox(string message)
        {
            textBox2.Text += localuser + ":" + message + "\n";
        }

        public void WriteTextBoxDes(string message)
        {
            textBox2.Text += desti + ":" + message + "\n";
        }
    }
}